package com.david.webtest

import android.graphics.Bitmap
import android.os.Bundle
import android.webkit.WebSettings
import android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity

class WebCacheTestActivity: AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_cache_test)
        findViewById<WebView>(R.id.webview).apply {
            settings.javaScriptEnabled = true
            //settings.setRenderPriority(WebSettings.RenderPriority.HIGH);//
            //getSettings().setCacheMode(WebSettings.LOAD_DEFAULT) //设置 缓存模式

            settings.blockNetworkImage = true//先阻止图片加载，在pagefinish后在允许加载
            // 开启 DOM storage API 功能
            settings.domStorageEnabled = true
            //开启 database storage API 功能
            settings.databaseEnabled = true
            //val cacheDirPath = cacheDir.absolutePath

            //设置数据库缓存路径
            //getSettings().setGeolocationDatabasePath(cacheDirPath)
            //设置  Application Caches 缓存目录
            //getSettings().setAppCachePath(cacheDirPath)
            //开启 Application Caches 功能
            settings.cacheMode = LOAD_CACHE_ELSE_NETWORK//第一次加载成功后即缓存下来了，后面没网也可以访问；要更新时可在链接后面追加个参数或参数改变下

            webViewClient = object : WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                }
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    settings.blockNetworkImage = false
                }
            }
            loadUrl("https://juejin.cn/post/7307723901529374757")
            //loadUrl("https://juejin.cn/post/7070849501166059551")
        }
    }
}